package com.phiture.erp.finance.web.controller.admin;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import com.phiture.erp.basic.api.pojo.resp.ErpSupplierResp;
import com.phiture.erp.basic.api.service.ErpSupplierApi;
import com.phiture.erp.finance.core.manage.ErpFinanceStatementManage;
import com.phiture.erp.finance.core.pojo.dto.ErpGenerateFinanceStatementDTO;
import com.phiture.erp.finance.core.pojo.dto.ErpRemoveFinanceStatementDTO;
import com.phiture.erp.finance.core.pojo.dto.PageErpFinanceStatementDTO;
import com.phiture.erp.finance.core.pojo.vo.ErpFinanceStatementPageReqVO;
import com.phiture.erp.finance.core.pojo.vo.ErpFinanceStatementRespVO;
import com.phiture.erp.finance.core.pojo.vo.ErpFinanceStatementSaveReqVO;
import com.phiture.erp.finance.core.pojo.vo.ErpFinanceStatementVO;
import com.phiture.erp.finance.core.service.ErpFinanceStatementService;
import com.phiture.erp.finance.dal.entity.ErpFinanceStatementDO;
import com.phiture.erp.finance.dal.entity.ErpFinanceStatementItemsDO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.GENERATE;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;


@Tag(name = "管理后台 - 对账单")
@RestController
@RequiredArgsConstructor
@RequestMapping("/erp/finance-statement")
public class ErpFinanceStatementController {
    private final ErpFinanceStatementService financeStatementService;
    private final ErpSupplierApi supplierApi;
    private final ErpFinanceStatementManage financeStatementManage;


    @PostMapping("/create")
    @Operation(summary = "创建对账单")
    @PreAuthorize("@ss.hasPermission('erp:finance-statement:create')")
    public CommonResult<Long> createFinanceStatement(@Valid @RequestBody ErpFinanceStatementSaveReqVO createReqVO) {
        return success(financeStatementService.createFinanceStatement(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新对账单")
    @PreAuthorize("@ss.hasPermission('erp:finance-statement:update')")
    public CommonResult<Boolean> updateFinanceStatement(@Valid @RequestBody ErpFinanceStatementSaveReqVO updateReqVO) {
        financeStatementService.updateFinanceStatement(updateReqVO);
        return success(true);
    }

    @PutMapping("/update-status")
    @Operation(summary = "更新对账单的状态")
    @PreAuthorize("@ss.hasPermission('erp:finance-statement:update-status')")
    public CommonResult<Boolean> updateFinanceStatementStatus(@RequestParam("id") Long id,
                                                        @RequestParam("status") Integer status) {
        financeStatementService.updateFinanceStatementStatus(id, status);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除对账单")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('erp:finance-statement:delete')")
    public CommonResult<Boolean> deleteFinanceStatement(@RequestParam("id") Long id, @RequestParam("type") Integer type) {
        financeStatementManage.removeFinanceStatement(new ErpRemoveFinanceStatementDTO(id, type));
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得对账单")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('erp:finance-statement:query')")
    public CommonResult<ErpFinanceStatementRespVO> getFinanceStatement(@RequestParam("id") Long id) {
        ErpFinanceStatementDO financeStatement = financeStatementService.getFinanceStatement(id);
        return success(BeanUtils.toBean(financeStatement, ErpFinanceStatementRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得对账单分页")
    @PreAuthorize("@ss.hasPermission('erp:finance-statement:query')")
    public CommonResult<PageResult<ErpFinanceStatementRespVO>> getFinanceStatementPage(@Valid ErpFinanceStatementPageReqVO pageReqVO) {
        PageResult<ErpFinanceStatementDO> pageResult = financeStatementService.getFinanceStatementPage(pageReqVO);
        return success(buildPageResult(pageResult));
    }

    private PageResult<ErpFinanceStatementRespVO> buildPageResult(PageResult<ErpFinanceStatementDO> pageResult) {
        if (pageResult.getList().isEmpty()) {
            return BeanUtils.toBean(pageResult, ErpFinanceStatementRespVO.class);
        }
        // 转换为 VO
        List<ErpFinanceStatementRespVO> list = BeanUtils.toBean(pageResult.getList(), ErpFinanceStatementRespVO.class);
        // 过滤出结果中的供应商ID
        List<Long> supplierIds = pageResult.getList().stream()
                .map(ErpFinanceStatementDO::getTransactionUserId)
                .distinct()
                .collect(Collectors.toList());
        // 调用供应商服务获取供应商名称
        Map<Long, ErpSupplierResp> supplierRespMap = supplierApi.getSupplierMap(supplierIds);

        // 填充供应商名称
        list.forEach(statement -> {
            MapUtils.findAndThen(supplierRespMap, statement.getTransactionUserId(), supplierResp -> {
                statement.setTransactionUserName(supplierResp.getName());
            });
        });

        return new PageResult<>(list, pageResult.getTotal());
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出对账单 Excel")
    @PreAuthorize("@ss.hasPermission('erp:finance-statement:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportFinanceStatementExcel(@Valid ErpFinanceStatementPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ErpFinanceStatementDO> list = financeStatementService.getFinanceStatementPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "对账单.xls", "数据", ErpFinanceStatementRespVO.class,
                        BeanUtils.toBean(list, ErpFinanceStatementRespVO.class));
    }

    @GetMapping("/generate")
    @Operation(summary = "生成对账单")
    @ApiAccessLog(operateType = GENERATE)
    public CommonResult<Boolean> generateFinanceStatement(@Valid ErpGenerateFinanceStatementDTO dto) {
        return success(financeStatementManage.generateFinanceStatement(dto));
    }

    // ==================== 子表（对账单明细） ====================

    @GetMapping("/finance-statement-items/list-by-statement-id")
    @Operation(summary = "获得对账单明细列表")
    @Parameter(name = "statementId", description = "对账单 ID")
    @PreAuthorize("@ss.hasPermission('erp:finance-statement:query')")
    public CommonResult<List<ErpFinanceStatementItemsDO>> getFinanceStatementItemsListByStatementId(@RequestParam("statementId") Long statementId) {
        return success(financeStatementService.getFinanceStatementItemsListByStatementId(statementId));
    }


    @GetMapping("/pageFinanceStatement")
    @Operation(summary = "获得对账单分页")
    @PreAuthorize("@ss.hasPermission('erp:finance-statement:query')")
    public CommonResult<PageResult<ErpFinanceStatementVO>> pageFinanceStatement(@Valid PageErpFinanceStatementDTO dto){
        return success(financeStatementService.pageFinanceStatement(dto));
    }

}